<template>
	<scroll-view style="height: 100vh;" scroll-y="true" refresher-enabled="true"
		:refresher-triggered="triggered" @refresherrefresh="onRestore">
		<view class="cu-list menu-avatar">
			<view class="cu-item" @click="chat_toAI">
				<view class="cu-avatar radius lg"
					:style="'background-image: url('+'http://8.146.208.139:3000/avator/1708001868981.png'+');'"></view>
				<view class="content">
					<view class="text-pink">
						<view class="text-cut" style="color: black;">科大讯飞</view>
					</view>
					<view class="text-gray text-sm flex">
						<view class="text-cut">欢迎与我交流！</view>
					</view>
				</view>
				<view class="action">
					<view class="text-grey text-xs">22:20</view>
					<!-- <view class="cu-tag round bg-red sm">5</view> -->
				</view>
			</view>
		</view>


		<view class="cu-list menu-avatar" v-for="(item,index) in mes" key="index">
			<view class="cu-item" @click="chat_detail(item)">
				<view class="cu-avatar radius lg" :style="'background-image: url(' + item.src + ');'"></view>
				<view class="content">
					<view class="text-pink">
						<view class="text-cut" style="color: black;">{{item.name}}</view>
					</view>
					<view class="text-gray text-sm flex">
						<view class="text-cut">{{item.content}}</view>
					</view>
				</view>
				<view class="action">
					<view class="text-grey text-xs">{{item.time}}</view>
					<view class="cu-tag round bg-red sm" v-show='item.new'></view>
				</view>
			</view>
		</view>
	</scroll-view>
</template>

<script>
	import chat from '@/subpkg/chat_detail/chat_detail.vue'
	import {
		getothermessage,
		getchatHistroyUser
	} from '@/store/api.js'
	export default {
		components: {
			chat,
		},
		onHide() {
			console.log(this.mes)
			uni.setStorageSync('chat_History_page', this.mes)
		},
		beforeDestroy() {
			console.log('要被关了')
		},
		mounted() {
			// uni.showLoading({
			// 	title:'加载中'
			// })
			uni.$on('closeWs',values=>{
				clearTimeout(this.TT)
				uni.hideLoading()
			})
			uni.$on('trunFales', values => {
				if (this.mes.find(item => item.userid == values))
					this.mes.find(item => item.userid == values).new = false
			})
			uni.$on('sendmsg', values => {
				if (this.mes.find(item => item.userid == values.userid)) {
					let temp = this.mes.find(item => item.userid == values.userid)
					this.mes = this.mes.filter(item => item.userid != values.userid)
					temp.content = values.content.substring(0, 10)
					temp.new = false
					temp.time = this.formatTime(values.time)
					this.mes.unshift(temp)
				} else {
					getothermessage(values.userid).then((res) => {
						console.log('这是对方信息')
						console.log(res.data.data)
						this.mes.unshift({
							name: res.data.data.userName,
							src: res.data.data.avatar,
							userid: values.userid,
							content: values.content.substring(0, 10),
							time: this.formatTime(values.time),
							new: false
						})
					})
				}
			})
			if (uni.getStorageSync('chat_History_page')) {
				let token = uni.getStorageSync('a_tk')
				this.mes = uni.getStorageSync('chat_History_page')
				uni.hideLoading()
				uni.connectSocket({
					url: `wss://meet.ysyxmy.top/web/socket?access_token=${token}`,
					success() {
						uni.setStorageSync('AlreadyConnect', true)
						console.log(uni.getStorageSync('detail'))
						if (uni.getStorageSync('detail')) {
							let value = JSON.parse(uni.getStorageSync('detail'))
							uni.removeStorage({
								key: 'detail'
							})
							uni.navigateTo({
								url: `/subpkg/chat_detail/chat_detail?name=${value.name}&src=${value.avator}&userid=${value.userid}`
							})
						}
					}
				});
			} else {
				uni.showLoading({
					title: '数据加载中'
				})
				getchatHistroyUser().then(res => {
					console.log(res)
					if(res.data.data.length>0){
						res.data.data.forEach(item => {
							if (!this.mes.find(it => item.userid == it.userid)){
								this.mes.unshift({
									name: item.userName,
									src: item.avatar,
									userid: item.id,
									content: '',
									time: '',
									new: false
								})
							}
						})
					}
			
					let token = uni.getStorageSync('a_tk')
					uni.connectSocket({
						url: `wss://meet.ysyxmy.top/web/socket?access_token=${token}`,
						success() {
							uni.setStorageSync('AlreadyConnect', true)
							console.log(uni.getStorageSync('detail'))
							if (uni.getStorageSync('detail')) {
								let value = JSON.parse(uni.getStorageSync('detail'))
								uni.removeStorage({
									key: 'detail'
								})
								uni.navigateTo({
									url: `/subpkg/chat_detail/chat_detail?name=${value.name}&src=${value.avator}&userid=${value.userid}`
								})
							}
						}
					});
					uni.hideLoading()
				}).catch(err => {
					console.log(err)
				})
			}
			let token = uni.getStorageSync('a_tk')
			uni.onSocketOpen((res)=> {
				uni.hideLoading()
				console.log('连接成功！')
				this.sendPing()
				uni.setStorageSync('AlreadyConnect', true)
				console.log(uni.getStorageSync('detail'))
				if (uni.getStorageSync('detail')) {
					let value = JSON.parse(uni.getStorageSync('detail'))
					uni.removeStorage({
						key: 'detail'
					})
					uni.navigateTo({
						url: `/subpkg/chat_detail/chat_detail?name=${value.name}&src=${value.avator}&userid=${value.userid}`
					})
				}
			});
			uni.onSocketError(function(err) {
				console.log(err);
				console.log('WebSocket 已关闭！');
			});
			uni.onSocketClose(function(res) {
				console.log('WebSocket 已关闭！');
				clearTimeout(this.TT)
				console.log(res)
				if (res.code == 1008) {
					refreshToken()
				}
				let token = uni.getStorageSync('a_tk')
				uni.setStorageSync('AlreadyConnect', false)
			});
			uni.onSocketMessage((res) => {
				try {
					if(res.data=='pong'){
						clearTimeout(this.TT)
						this.sendPing()
						return
					}
					const ress = JSON.parse(res.data);
					console.log(ress);
					if (ress.type == '999')
						return
					if (ress && ress.message && ress.message.uuid) {
						console.log('收到uuid：' + ress.message.uuid);
						uni.sendSocketMessage({
							data: JSON.stringify({
								type: "999",
								message: {
									content: "success",
									uuid: ress.message.uuid
								}
							}),
							success: () => {
								// console.log('回应消息发送成功');
							},
							fail: (err) => {
								// console.error('回应消息发送失败', err);
							}
						});
		
		
						uni.$emit('Look', {
							type: ress.type,
							mes: ress.message,
							uuid: ress.message.uuid
						})
						getothermessage(ress.message.sendFrom).then((res) => {
							if (ress.type == 1) {
								if (this.mes.find(item => item.userid == ress.message.sendFrom)) {
									this.mes = this.mes.filter(item => item.userid != ress.message
										.sendFrom)
								}
								this.mes.unshift({
									name: res.data.data.userName,
									src: res.data.data.avatar,
									userid: ress.message.sendFrom,
									content: '[邀请]',
									time: this.formatTime(ress.message.timestamp),
									new: true
								})
							} else if (ress.type == 2 || ress.type == 3) {
								if (this.mes.find(item => item.userid == ress.message.sendFrom)) {
									this.mes = this.mes.filter(item => item.userid != ress.message
										.sendFrom)
								}
								this.mes.unshift({
									name: res.data.data.userName,
									src: res.data.data.avatar,
									userid: ress.message.sendFrom,
									content: '[回复]',
									time: this.formatTime(ress.message.timestamp),
									new: true
								})
							} else {
								if (this.mes.find(item => item.userid == ress.message.sendFrom)) {
									this.mes = this.mes.filter(item => item.userid != ress.message
										.sendFrom)
								}
								this.mes.unshift({
									name: res.data.data.userName,
									src: res.data.data.avatar,
									userid: ress.message.sendFrom,
									content: ress.message.content.startsWith('**/img/**') ?
										'[图片]' : ress.message.content.substring(0, 25) + '···',
									time: this.formatTime(ress.message.timestamp),
									new: true
								})
							}
		
						})
					}
				} catch (error) {
					console.error('解析消息时发生错误', error);
				}
			});
		
		},
		data() {
			return {
				mes: [],
				TT:null,
				triggered:false
			};
		},
		methods: {
			onRestore(){
				this.triggered=true
				clearTimeout(this.TT)
				let token=uni.getStorageSync('a_tk')
				uni.connectSocket({
					url: `wss://meet.ysyxmy.top/web/socket?access_token=${token}`,
					success: (res) => {
						this.sendPing()
						uni.setStorageSync('AlreadyConnect', true)
						console.log(uni.getStorageSync('detail'))
						if (uni.getStorageSync('detail')) {
							let value = JSON.parse(uni.getStorageSync('detail'))
							uni.removeStorage({
								key: 'detail'
							})
							uni.navigateTo({
								url: `/subpkg/chat_detail/chat_detail?name=${value.name}&src=${value.avator}&userid=${value.userid}`
							})
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '连接失败，请重新登录',
							icon: 'error',
							duration: 2000
						})
					}
				});
				setTimeout(()=>{
					this.triggered=false
				},1000)
			},
			sendPing() {
				console.log('ping')
				uni.sendSocketMessage({
					data: 'ping'
				});
			
				this.TT = setTimeout(() => {
					let token = uni.getStorageSync('a_tk')
					uni.connectSocket({
						url: `wss://meet.ysyxmy.top/web/socket?access_token=${token}`,
						success() {
							uni.setStorageSync('AlreadyConnect', true)
							console.log(uni.getStorageSync('detail'))
							if (uni.getStorageSync('detail')) {
								let value = JSON.parse(uni.getStorageSync('detail'))
								uni.removeStorage({
									key: 'detail'
								})
								uni.navigateTo({
									url: `/subpkg/chat_detail/chat_detail?name=${value.name}&src=${value.avator}&userid=${value.userid}`
								})
							}
						}
					});
				}, 2000)
			},
			formatTime(timestamp) {
				// 创建一个新的 Date 对象并传入时间戳
				const date = new Date(timestamp);

				// 获取小时部分，并确保将单个小时数前面的0添加上
				const hours = String(date.getHours()).padStart(2, '0');

				// 获取分钟部分，并确保将单个分钟数前面的0添加上
				const minutes = String(date.getMinutes()).padStart(2, '0');

				// 将小时和分钟组合成"hh:mm"格式的字符串
				const timeString = `${hours}:${minutes}`;

				// 返回格式化后的时间字符串
				return timeString;
			},
			chat_toAI() {
				uni.navigateTo({
					url: `/subpkg/chat_gpt/chat_gpt`
				})
			},
			chat_detail(item) {
				console.log(item)
				this.mes.find(r => r == item).new = false
				uni.navigateTo({
					url: `/subpkg/chat_detail/chat_detail?name=${item.name}&src=${item.src}&userid=${item.userid}`
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.cu-list+.cu-list {
		margin-top: 0;
	}

	.chatli {
		width: 100%;
		height: 100rpx;
		background-color: white;
		margin: 3rpx auto;
		display: flex;
		border-top: 1px solid black;
		border-bottom: 1px solid black;
		// margin: 10prx 0;
	}

	.chatli:nth-child(1) {
		margin-top: 30rpx;
	}

	.img {
		width: 14vw;
		padding: 2%;
		// height: 14vw;
		display: flex;
		text-align: center;
		display: flex;
		vertical-align: middle;
		// border-right: 1px solid black;
	}

	.imgg {
		width: 100%;
		height: 100%;
		border-radius: 75%;
	}

	.id {
		font-size: 5vw;
	}
</style>